import ipaddress
import random
from flask import Flask, request, Response
from log import logger
import time
from datetime import datetime, timedelta
from prometheus_client import Counter, Histogram, generate_latest, CONTENT_TYPE_LATEST, Gauge

# 定义 Prometheus 指标
# 请求总数
request_total = Counter("request_total", "Total number of requests", ["method", "endpoint"])

# 请求速率 (通常直接从总数计算)
request_rate = Gauge("request_rate", "Rate of requests per second", ["method", "endpoint"])

# 请求延迟 (使用直方图来跟踪延迟分布)
request_latency = Histogram("request_latency_seconds", "Request latency in seconds", ["endpoint"])

# 错误率
error_rate = Counter("error_rate", "Total number of error responses", ["method", "endpoint", "status_code"])

# 请求大小和响应大小
request_size = Histogram("request_size_bytes", "Request size in bytes", ["endpoint"])
response_size = Histogram("response_size_bytes", "Response size in bytes", ["endpoint"])

app = Flask(__name__)


def random_value(value):
    """
    传入生成随机值的列表，随机返回其中一个值
    """
    index = random.randint(0, len(value) - 1)
    return value[index]


def process_request():
    """模拟处理请求并记录指标"""


def log_demo():
    content = {
        'access_status': random_value(
            [200] * 10 + [201] * 3 + [301, 400, 401, 403, 404, 500, 502, 503, 504]
        ),
        'request_method': random_value(['GET'] * 10 + ['POST'] * 5 + ['PUT', 'DELETE']),
        'request_uri': random_value(['/login/', '/account/', '/public/', '/management/']),
        'request_length': random.randint(1, 99),
        'remote_address': str(ipaddress.ip_address(
            random.randint(int(ipaddress.ip_address('101.0.0.1')), int(ipaddress.ip_address('223.255.255.254')))
        )),
        'server_name': f"{random_value(['cm', 'cu'])}-{random.randint(1, 9)}.cn",
        'time_start': (datetime.now() - timedelta(milliseconds=random.randint(1, 1000))).isoformat(timespec='milliseconds') + "+08:00",
        'time_finish': (datetime.now() + timedelta(milliseconds=random.randint(1, 1000))).isoformat(timespec='milliseconds') + "+08:00",
        'http_user_agent': random_value([
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Firefox/78.0',
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/91.0.4472.124',
            'Mozilla/5.0 (Linux; Android 9; MX10 PRO) Chrome/94.0.4606.71',
            'Mozilla/5.0 (iPhone; CPU iPhone OS 11_4_1) Safari/604.1',
            'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) Safari/604.3.5',
            'Mozilla/5.0 (X11; Linux x86_64) Firefox/78.0'
        ]),
    }
    if content['access_status'] in {500, 502, 503, 504}:
        logger.error(content)
    elif content['access_status'] in {400, 401, 403, 404}:
        logger.warning(content)
    else:
        for _ in range(random.choice([1, 2, 3, 4, 5])):
            logger.info(content)

    return content

@app.route('/')
def index():
    start = time.time()
    # 随机生成请求大小和响应大小
    req_size = random.randint(100, 1000)
    resp_size = random.randint(100, 2000)

    # 模拟请求速率（通过更新 request_rate）
    request_rate.labels(method="GET", endpoint="/example").set(random.uniform(0.5, 2.0))

    # 模拟一些延迟
    time.sleep(random.uniform(0.1, 0.3))

    # 模拟成功或错误的请求
    status_code = 200 if random.random() > 0.1 else 500

    # 更新请求总数和错误率（如果有错误）
    request_total.labels(method="GET", endpoint="/example").inc()
    if status_code != 200:
        error_rate.labels(method="GET", endpoint="/example", status_code=str(status_code)).inc()

    # 更新请求延迟
    request_latency.labels(endpoint="/example").observe(time.time() - start)

    # 更新请求大小和响应大小
    request_size.labels(endpoint="/example").observe(req_size)
    response_size.labels(endpoint="/example").observe(resp_size)
    # 模拟随机写入日志
    return log_demo()


@app.route('/health')
def health():
    return 'ok'


@app.route('/metrics')
def metrics():
    # 返回所有指标的当前值
    return Response(generate_latest(), mimetype=CONTENT_TYPE_LATEST)


if __name__ == '__main__':
    app.run()
